<template>
	<div class="search-result-list-container">
		<van-row class="search0-body">
			<van-col :span="22">
				<van-field
					v-model="displayText"
					:label="label"
					:required="required"
					:readonly="readonly"
					input-align="left"
					:placeholder="placeholder"
					clearable
					@update:model-value="handleInputSearch"
					@clear="handleClear"
				/>
			</van-col>
			<van-col :span="2">
				<van-icon name="search" class="list-container-search" />
			</van-col>
		</van-row>

		<van-row v-if="showList" class="list-container">
			<van-col :span="24">
				<van-cell v-for="(item, index) in itemData" :key="index" :title="item[showText]" class="value-class" clickable @click="toggle(item, index)" />
			</van-col>
		</van-row>

		<van-row v-if="itemData.length === 0 && showList" class="list-container">
			<van-col :span="24">
				<div class="to-add-data" @click="toAdd">搜不到企业？去添加企业</div>
			</van-col>
		</van-row>
	</div>
</template>

<script>
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { Toast } from 'vant'
import { post } from '@/api/request'

const debounce = (func, delay = 300) => {
	let timeoutId
	return (...args) => {
		clearTimeout(timeoutId)
		timeoutId = setTimeout(() => func.apply(null, args), delay)
	}
}

export default {
	name: 'SearchSelect',
	props: {
		modelValue: { type: [String, Number], default: '' },
		label: { type: String, default: '' },
		required: { type: Boolean, default: false },
		readonly: { type: Boolean, default: false },
		key: { type: String, default: '' },
		defaultText: { type: String, default: '' },
		showText: { type: String, default: 'name' },
		chooseValue: { type: String, default: 'id' },
		httpUrl: { type: String, default: '' },
		httpParams: { type: Object, default: () => ({}) },
		placeholder: { type: String, default: '请输入搜索' },
	},
	emits: ['update:modelValue', 'onListSelectedChange'],
	setup(props, { emit }) {
		const router = useRouter()

		const itemData = ref([])
		const itemDataAll = ref([])
		const dataSelectedInfo = ref({})
		const showList = ref(false)
		const searchText = ref('')

		const displayText = computed({
			get() {
				// 优先显示已选中项目的文本，否则显示搜索文本
				if (dataSelectedInfo.value && dataSelectedInfo.value[props.showText]) {
					return dataSelectedInfo.value[props.showText]
				}
				return searchText.value
			},
			set(val) {
				searchText.value = val || ''
				// 当输入为空时，清除选中状态
				if (!val) {
					dataSelectedInfo.value = {}
					emit('update:modelValue', '')
					emit('onListSelectedChange', {
						key: props.key,
						value: '',
						dataSelectedInfo: {},
					})
				}
			},
		})

		const queryData = async (params = {}) => {
			if (!props.httpUrl) return []

			try {
				itemData.value = []

				const requestParams = { ...props.httpParams, ...params }
				const res = await post(props.httpUrl, requestParams)

				if (res.code === '0' && Array.isArray(res.data)) {
					itemData.value = res.data

					if (itemDataAll.value.length === 0 || props.httpParams.reLoadData) {
						itemDataAll.value = res.data
					}

					await nextTick()
					initData()

					return res.data
				} else {
					throw new Error(res.msg || '查询失败')
				}
			} catch (error) {
				console.error('查询数据失败:', error)
				Toast({ type: 'fail', message: '获取列表失败' })
				itemData.value = []
				return []
			}
		}

		const debouncedQuery = debounce((searchParams) => {
			queryData(searchParams)
		}, 300)

		const initData = () => {
			setTimeout(() => {
				if (props.modelValue && itemDataAll.value.length > 0) {
					const selectedItem = itemDataAll.value.find((item) => item[props.chooseValue] === props.modelValue)

					if (selectedItem) {
						dataSelectedInfo.value = selectedItem
						emit('onListSelectedChange', {
							key: props.key,
							value: props.modelValue,
							dataSelectedInfo: selectedItem,
						})
					}
				}
			}, 200)
		}

		const handleInputSearch = (value) => {
			console.log('搜索输入:', value, typeof value)

			// 确保 value 是字符串，如果是事件对象则获取 target.value
			const searchValue = typeof value === 'string' ? value : value?.target?.value || ''

			searchText.value = searchValue
			showList.value = true

			// 传递正确的搜索文本参数
			debouncedQuery({ searchText: searchValue })
		}

		const handleClear = () => {
			console.log('清除搜索')
			searchText.value = ''
			dataSelectedInfo.value = {}
			showList.value = false

			// 发出清除事件
			emit('update:modelValue', '')
			emit('onListSelectedChange', {
				key: props.key,
				value: '',
				dataSelectedInfo: {},
			})
		}

		const toggle = (item, index) => {
			console.log('选择项目:', item)

			const selectedValue = item[props.chooseValue]

			dataSelectedInfo.value = item
			searchText.value = ''
			showList.value = false

			emit('update:modelValue', selectedValue)
			emit('onListSelectedChange', {
				key: props.key,
				value: selectedValue,
				dataSelectedInfo: item,
			})
		}

		const toAdd = () => {
			console.log('跳转到添加页面')
			try {
				router.push('/company/add')
			} catch (error) {
				window.location.href = '#/company/add'
			}
		}

		watch(
			() => props.modelValue,
			(newValue, oldValue) => {
				if (newValue !== oldValue && newValue && itemDataAll.value.length > 0) {
					initData()
				}
			},
			{ immediate: true }
		)

		watch(
			() => props.httpParams,
			(newParams, oldParams) => {
				if (JSON.stringify(newParams) !== JSON.stringify(oldParams)) {
					queryData()
				}
			},
			{ deep: true, immediate: false }
		)

		onMounted(() => {
			queryData()
		})

		return {
			itemData,
			itemDataAll,
			dataSelectedInfo,
			showList,
			displayText,
			searchText,
			handleInputSearch,
			handleClear,
			toggle,
			toAdd,
		}
	},
}
</script>

<style lang="less" scoped>
.search-result-list-container {
	position: relative;
}

.value-class {
	flex: none !important;
}

.list-container {
	position: absolute;
	z-index: 100;
	background: #fff;
	width: 105%;
	text-align: left;
	top: 50px;
	height: 400px;
	overflow: auto;
	border: 1px solid #ebedf0;
	border-radius: 6px;
	box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.list-container-search {
	position: absolute;
	right: 20px;
	top: 15px;
	color: #969799;
}

.check-hide {
	display: none;
}

.check-active {
	display: block;
}

.to-add-data {
	text-align: center;
	color: rgba(78, 142, 236, 0.867);
	padding: 12px;
	cursor: pointer;
	border-top: 1px solid #ebedf0;
}

.to-add-data:hover {
	background-color: #f7f8fa;
}

.search0-body {
	position: relative;
}
</style>